<script>
export default {
  name: 'SpuEdit'
}
</script>
<script setup>
import { useProductStore } from '@/store/modules/product'
import { GET_TOKEN } from '@/utils/token'
import { storeToRefs } from 'pinia'
import $api from '@/api/index'
import { ref, onMounted, nextTick, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { inject } from 'vue'

const productStore = useProductStore()
const { categoryIdData, spuFormData } = storeToRefs(productStore)

onMounted(() => {
  reqAllTrademarkList()
  reqBaseSaleAttrList()
  if (spuFormData.value.id) {
    reqSpuImageList(spuFormData.value.id)
    reqSpuSaleAttrList(spuFormData.value.id)
  }
})

// 获取全部品牌列表
const reqAllTrademarkList = async function () {
  const result = await $api.product.spu.reqAllTrademarkList()
  if (result?.data?.code === 200) {
    allTrademarkList.value = result.data.data

    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 获取全部spu销售属性
const reqBaseSaleAttrList = async function () {
  const result = await $api.product.spu.reqBaseSaleAttrList()
  if (result?.data?.code === 200) {
    allBaseSaleAttrList.value = result.data.data

    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 获取指定spuId的图片列表
const reqSpuImageList = async function (spuId) {
  const result = await $api.product.spu.reqSpuImageList(spuId)
  if (result?.data?.code === 200) {
    fileList.value = result.data.data.map(item => {
      item.url = item.imgUrl
      return item
    })

    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 获取指定spuId的全部的已有销售属性
const reqSpuSaleAttrList = async function (spuId) {
  const result = await $api.product.spu.reqSpuSaleAttrList(spuId)
  if (result?.data?.code === 200) {
    spuFormData.value.spuSaleAttrList = result.data.data

    return 'ok'
  } else {
    return Promise.reject(result?.data?.message)
  }
}

// 全部品牌数据
const allTrademarkList = ref([])

// 全部spu销售属性
const allBaseSaleAttrList = ref([])
// 选中的spu销售属性
const selectSaleAttr = ref(null)
// 剩下没被选中的spu销售属性
const surplusSaleAttr = computed(() => {
  return allBaseSaleAttrList.value.filter(
    item =>
      !spuFormData.value.spuSaleAttrList?.some(someItem => item.name === someItem.saleAttrName)
  )
})

// 添加销售属性函数
const addSpuSaleAttrFn = function () {
  spuFormData.value.spuSaleAttrList.push({
    baseSaleAttrId: selectSaleAttr.value.id,
    saleAttrName: selectSaleAttr.value.name,
    spuSaleAttrValueList: []
  })
  // 初始化
  selectSaleAttr.value = null
}
// 删除销售属性函数
const removeSpuSaleAttrFn = function (index) {
  spuFormData.value.spuSaleAttrList.splice(index, 1)
}

// 添加销售属性 值 临时保存变量
const addSpuSaleAttrValueTmp = ref()
// 添加销售属性 值 临时输入框出现判定
const addSpuSaleAttrValueTmpInput = ref([])
// 添加销售属性 值 临时输入框DOM
const addSpuSaleAttrValueTmpInputRef = ref()
// 显示临时输入框函数
const showAddSpuSaleAttrValueTmpInputFn = function (index) {
  addSpuSaleAttrValueTmpInput.value[index] = true
  nextTick(() => {
    addSpuSaleAttrValueTmpInputRef.value.focus()
  })
}
// 添加销售属性 值 函数
const addSpuSaleAttrValueFn = function (row, index) {
  // 输入框没内容就直接返回
  if (!addSpuSaleAttrValueTmp.value.trim()) {
    addSpuSaleAttrValueTmp.value = ''
    addSpuSaleAttrValueTmpInput.value[index] = false
    return
  }
  // 检查是否有相同项
  const isSome = spuFormData.value.spuSaleAttrList[index].spuSaleAttrValueList.some(
    item => item.saleAttrValueName === addSpuSaleAttrValueTmp.value.trim()
  )
  if (isSome) {
    ElMessage.error('不能有相同的值')
    nextTick(() => {
      addSpuSaleAttrValueTmpInputRef.value.focus()
    })
    return
  }
  // push数据
  spuFormData.value.spuSaleAttrList[index].spuSaleAttrValueList.push({
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: addSpuSaleAttrValueTmp.value.trim()
  })
  // 初始化变量
  addSpuSaleAttrValueTmp.value = ''
  addSpuSaleAttrValueTmpInput.value[index] = false
}
// 删除销售属性 值 函数
const removeSpuSaleAttrValueFn = function (listIndex, tagIndex) {
  // 根据索引删除
  spuFormData.value.spuSaleAttrList[listIndex].spuSaleAttrValueList.splice(tagIndex, 1)
}

// 图片相关
// 上传图片地址
const imgUpLoadUrl = import.meta.env.VITE_SERVER + '/admin/product/fileUpload'
// 上传图片请求头
const imgUpLoadHeaders = { token: GET_TOKEN() }
const fileList = ref([])

// 放大图片地址
const dialogImageUrl = ref('')
// 放大判定
const dialogVisible = ref(false)
// 删除图片回调
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
// 放大图片回调
const handlePictureCardPreview = uploadFile => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}

const reqSpuInfoList = inject('reqSpuInfoList')
// 保存spu信息
const saveSpuInfo = async function () {
  // 整合数据
  // category3Id
  spuFormData.value.category3Id = categoryIdData.value.id3
  // spuImageList
  spuFormData.value.spuImageList = fileList.value.map(item => {
    let result
    if (item.imgName && item.imgUrl) {
      result = item
    } else {
      result = {
        imgName: item.name,
        imgUrl: import.meta.env.VITE_SERVER + item.response.data.replace('/api', '')
      }
    }
    return result
  })
  try {
    await productStore.saveSpuEditor(spuFormData.value)
    ElMessage.success('SPU保存成功')
    reqSpuInfoList()
  } catch (error) {
    ElMessage.error('SPU保存失败')
  }
}

// 允许保存判定
const allowSaving = computed(() => {
  return (
    !!spuFormData.value.spuName &&
    !!spuFormData.value.description &&
    !!spuFormData.value.tmId &&
    fileList.value.length > 0 &&
    spuFormData.value.spuSaleAttrList?.length > 0 &&
    spuFormData.value.spuSaleAttrList[0]?.spuSaleAttrValueList.length > 0
  )
})
</script>

<template>
  <div>
    <el-card class="marginTop20px">
      <el-form label-width="120px">
        <!-- SPU名称 -->
        <el-form-item
          label="SPU名称"
          required
        >
          <el-input
            v-model="spuFormData.spuName"
            class="width250px"
            placeholder="请填写你的SPU名字"
          />
        </el-form-item>
        <!-- SPU品牌 -->
        <el-form-item
          label="SPU品牌"
          required
        >
          <el-select
            placeholder="请选择你的品牌"
            class="width250px"
            v-model="spuFormData.tmId"
          >
            <el-option
              v-for="item in allTrademarkList"
              :key="item.id"
              :label="item.tmName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- SPU描述 -->
        <el-form-item
          label="SPU描述"
          required
        >
          <el-input
            type="textarea"
            resize="none"
            :rows="3"
            placeholder="请填写你的SPU描述"
            v-model="spuFormData.description"
          />
        </el-form-item>
        <!-- SPU照片 -->
        <el-form-item
          label="SPU照片"
          required
        >
          <el-upload
            v-model:file-list="fileList"
            :action="imgUpLoadUrl"
            :headers="imgUpLoadHeaders"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
          >
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>

          <el-dialog v-model="dialogVisible">
            <img
              w-full
              :src="dialogImageUrl"
              alt="Preview Image"
            />
          </el-dialog>
        </el-form-item>
        <!-- SPU销售属性 -->
        <el-form-item
          label="SPU销售属性"
          required
        >
          <el-select
            v-model="selectSaleAttr"
            :placeholder="
              surplusSaleAttr.length === 0 ? '无可选选项' : `还有${surplusSaleAttr.length}项未选择`
            "
            value-key="id"
            class="width250px marginRight20px"
          >
            <el-option
              v-for="item in surplusSaleAttr"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
          <el-button
            type="primary"
            icon="Plus"
            @click="addSpuSaleAttrFn"
            :disabled="!selectSaleAttr"
          >
            添加销售属性
          </el-button>
          <el-table
            :data="spuFormData.spuSaleAttrList"
            border
            stripe
            class="marginTopBottom20px"
          >
            <el-table-column
              type="index"
              width="80"
              label="序号"
              align="center"
            />
            <el-table-column
              prop="saleAttrName"
              label="属性名"
            />
            <el-table-column label="属性值">
              <template #="{ row, $index }">
                <el-tag
                  type="primary"
                  closable
                  class="marginRight20px"
                  v-for="(item, index) in row.spuSaleAttrValueList"
                  :key="index"
                  @close="removeSpuSaleAttrValueFn($index, index)"
                >
                  {{ item.saleAttrValueName }}
                </el-tag>
                <input
                  type="text"
                  v-if="addSpuSaleAttrValueTmpInput[$index]"
                  ref="addSpuSaleAttrValueTmpInputRef"
                  class="marginRight20px"
                  v-model="addSpuSaleAttrValueTmp"
                  @blur="addSpuSaleAttrValueFn(row, $index)"
                />
                <el-button
                  type="primary"
                  icon="Plus"
                  @click="showAddSpuSaleAttrValueTmpInputFn($index)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #="{ row, $index }">
                <el-popconfirm
                  :title="`你确定要删除 ${row.saleAttrName} 吗？`"
                  placement="top"
                  @confirm="removeSpuSaleAttrFn($index)"
                >
                  <template #reference>
                    <el-button
                      type="danger"
                      icon="Delete"
                    />
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="saveSpuInfo()"
            :disabled="!allowSaving"
            >保存</el-button
          >
          <el-button @click="productStore.closeSpuEditor()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
// start
</style>
